var mysql = require('mysql');

var pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '',
  port: 3306,
  database: 'zhixin',
  timezone: '08:00'
});

function doSQL(sql, params = []) {
  return new Promise((resolve, reject) => {
    // 从创建的连接池中获取到连接
    pool.getConnection((err, connection) => {
      if (err) {
        reject(err)
      } else {
        connection.query(sql, params, (error, data, fileds) => {
          connection.release();   // 释放数据库连接
          resolve({ error, data, fileds })
        })
      }
    })
  })
}

function handleResults(data, total, classify) {
  return JSON.stringify({
    success: true,
    errorCode: 0,
    code: 20000,
    msg: '数据请求成功',
    data,
    total,
    classify
  })
}

module.exports = {
  doSQL: doSQL,
  handleResults: handleResults
}